import { defineStore } from 'pinia'
import axios from 'axios'
import type { Post } from '@/types/Post' // 根据你实际路径修改
import { useUserStore } from '@/stores/user'
import type { Comment } from '@/types/comment'

export const usePostStore = defineStore('post', {
  
  state: () => ({
    posts: [] as Post[], // ✅ 指定类型为 Post[]
    allPosts: [] as Post[],
    currentPost: null as Post | null, // ✅ 已补充定义
    comments: [] as Comment[]  // ✅ 添加评论列表
  }),

  getters: {
    visiblePosts(state) {
      return state.posts.filter(post => !post.isDeleted)
    },
    userPosts: (state) => (userId: number) => {
      return state.posts.filter(p => p.userId === userId && !p.isDeleted)
    }
  },

  actions: {
    async fetchUserPosts(userId: number) {
      try {
        const res = await axios.get(`/api/knowledge/user/${userId}`)
        if (res.data.code === 200) {
          this.posts = res.data.data || []
        } else {
          console.error('获取用户帖子失败：', res.data.message)
          this.posts = [] // 清空列表以防旧数据残留
        }
      } catch (err) {
        console.error('获取用户帖子请求出错：', err)
        this.posts = []
      }
    },

    addPost(post: Post) {
      this.posts.unshift(post)
    },

    async deletePost(postId: number) {
      try {
        const res = await fetch(`/api/post/${postId}`, {
          method: 'DELETE'
        })

        const data = await res.json()

        if (data.code === 200) {
          // 从前端状态中移除该帖子（从 posts 和 allPosts 中同步删除）
          this.posts = this.posts.filter(p => p.knowledgeId !== postId)
          this.allPosts = this.allPosts.filter(p => p.knowledgeId !== postId)
          console.log('✅ 删除成功')
        } else {
          console.warn('❌ 删除失败：', data.message)
        }
      } catch (err) {
        console.error('❌ 删除请求出错：', err)
      }
    },

    async toggleLike(postId: number, userId: number) {
      try {
        const res = await fetch(`/api/post/${postId}/like?userId=${userId}`, {
          method: 'POST'
        });
        const data = await res.json();

        if (data.code === 200) {
          const post = this.allPosts.find(p => p.knowledgeId === postId);
          if (post) {
            post.likedBy = data.data.likedBy || [];
            post.likes = data.data.likes || 0;
          }
        } else {
          console.error('点赞失败：', data.message);
        }
      } catch (error) {
        console.error('点赞请求出错：', error);
      }
    },
    async toggleFavorite(postId: number, userId: number) {
      try {
        const res = await fetch(`/api/post/${postId}/favorite?userId=${userId}`, {
          method: 'POST'
        });
        const data = await res.json();

        if (data.code === 200) {
          const post = this.allPosts.find(p => p.knowledgeId === postId);
          if (post) {
            post.favoritedBy = data.data.favoritedBy || [];
            post.favorites = data.data.favorites || 0;
          }
        } else {
          console.error('收藏失败：', data.message);
        }
      } catch (error) {
        console.error('收藏请求出错：', error);
      }
    },

    async fetchAllPosts() {
      try {
        const res = await fetch('/api/post/all')
        const data = await res.json()
        if (data.code === 200) {
          this.allPosts = data.data.map((p: any) => ({
            ...p,
            comments: [], // 可选：用于占位，避免空值报错
            commentCount: p.commentCount || 0
          }))
        } else {
          console.error('帖子获取失败：', data.message)
        }
      } catch (err) {
        console.error('请求出错：', err)
      }
    },
    async addComment(payload: { knowledgeId: number; userId: number; content: string }) {
      try {
        const res = await axios.post(`/api/comment/add`, payload)
        if (res.data.code !== 200) {
          console.error('评论失败：', res.data.message)
        } else {
          await this.fetchComments(payload.knowledgeId) // ✅ 重新拉评论
        }
      } catch (err) {
        console.error('评论请求出错：', err)
      }
    },
    async fetchComments(postId: number) {
      try {
        const res = await axios.get(`/api/comment/post/${postId}`)
        this.comments = res.data.data
      } catch (err) {
        console.error('获取评论失败：', err)
      }
    },
    async fetchPostDetail(postId: number) {
      try {
        const res = await axios.get(`/api/post/${postId}`)
        if (res.data.code === 200) {
          const data = res.data.data
          this.currentPost = {
            ...data.post,
            nickname: data.nickname,
            avatar: data.avatar,
            comments: data.comments || [],
            images: [],
            favoritedBy: data.favoritedBy || [],
            favorites: data.favorites
          }
        } else {
          this.currentPost = null
          console.warn('帖子详情获取失败')
        }
      } catch (error) {
        console.error('获取帖子详情失败：', error)
        this.currentPost = null
      }
    },

    async deletePostReal(postId: number) {
      try {
        const res = await axios.delete(`/api/post/${postId}`)
        if (res.data.code === 200) {
          this.allPosts = this.allPosts.filter(p => p.knowledgeId !== postId)
          this.posts = this.posts.filter(p => p.knowledgeId !== postId)
          console.log('✅ 删除成功')
        } else {
          console.warn('删除失败：', res.data.message)
        }
      } catch (err) {
        console.error('删除请求失败：', err)
      }
    }
  }
})